/**
 * 中划线转小驼峰
 * @param {String} str
 */
const camelCase = (str) => {
  return str.replace(/-(.)/g, (_, w) => w.toUpperCase());
};

/**
 * 驼峰转下划线
 * @param {String} str
 */
const snakeCase = (str) => {
  return str
    .replace(/(?<=[^A-Z])[A-Z]/g, (w) => {
      return "_" + w.toLowerCase();
    })
    .toLowerCase();
};

/**
 * 大写首字母
 * @param {String} word
 */
const capitalize = (word) => {
  return word[0].toUpperCase() + word.slice(1);
};

/**
 * 超过长度显示...
 * @param {String} str 文字
 * @param {Number} maxLength 保留最大长度
 * @param {String} padding 填充
 * @returns {String}
 */
const ellipsis = (str = "", maxLength = 20, padding = ".") =>
  str.length > maxLength
    ? str.slice(0, maxLength - 3).padEnd(maxLength, padding)
    : str;

/**
 * 从对象建立URL参数
 * @param {Object} obj 参数对象
 * @returns {URLSearchParams}
 */
function buildParams(obj) {
  const params = new URLSearchParams();
  for (const key in obj) {
    const value = obj[key];
    if (value === undefined) continue;

    if (Array.isArray(value)) {
      value.forEach((v) => params.append(key, v));
      continue;
    }

    params.set(key, value);
  }
  return params;
}

/**
 * 格式化数字
 * @param {Number} num 待处理的数字
 * @param {String} delimiter 分隔符
 * @param {Number} splitLength 几位分割一次
 * @returns {String}
 */
function formatNumber(num, delimiter = "_", splitLength = 3) {
  if (num < 0) {
    return "-" + formatNumber(-num, delimiter, splitLength);
  }

  const level = 10 ** splitLength;

  let quotient = num,
    remainder = 0,
    res = "";
  do {
    remainder = quotient % level;
    quotient = Math.floor(quotient / level);
    res = remainder + ((res ? delimiter : "") + res);
  } while (quotient);

  return res;
}

export { buildParams, camelCase, capitalize, ellipsis, formatNumber, snakeCase };
